Imports FlickrNet
Imports System.Configuration
Imports System.Web.Configuration
Imports System.IO
Imports System.Drawing


Partial Public Class FlickrData
    Inherits System.Web.UI.Page
    Dim cacheConfig As CacheConfig
    Private Shared config As nFlickrViewerConfigurationSection = ConfigurationManager.GetSection("nFlickrViewer")

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim mode As String = Request("mode")
          If mode = "img" Then
            Dim size As String = Request("size")
            Dim image As String = Request("image")
            Dim url As String = ""

            If size = "thumb" Then
                url = image.Replace(".jpg", "_s.jpg") 'Request("imageThumbUrl")
            Else
                Select Case config.FlickrConfigurationElement.flickrImageSize
                    Case "small"
                        url = image.Replace(".jpg", "_m.jpg")
                    Case "med"
                        url = image
                    Case "large"
                        url = image.Replace(".jpg", "_b.jpg")

                End Select
            End If

            Response.StatusCode = 301
            Response.Status = "301 Moved Permanently"
            Response.AddHeader("Location", url)
        Else

            cacheConfig = cacheConfig.GetInstance()

            'add cache
            Dim imgPath = ""
            Dim thumbPath = ""

            If cacheConfig.DoUseCacheProp = False Then ' DoCreateCacheProp = False Then
                imgPath = "FlickrData.aspx?mode=img&amp;size=large&amp;image="
                thumbPath = "FlickrData.aspx?mode=img&amp;size=thumb&amp;image="
            Else
                imgPath = "images/"
                thumbPath = "thumbs/"
            End If


            'Dim imgPath As String = "images/"
            'Dim thumbPath As String = "thumbs/"

            Dim xml As String

            Dim f As Flickr = New Flickr(config.FlickrConfigurationElement.flickrApiKey)

            Dim searchOptions As PhotoSearchOptions = New PhotoSearchOptions()
            searchOptions.SortOrder = PhotoSearchSortOrder.InterestingnessDesc
            searchOptions.PerPage = config.FlickrConfigurationElement.flickrMaxNoResults
            Select Case config.FlickrConfigurationElement.flickrSortOrder
                Case "DatePostedAsc"
                    searchOptions.SortOrder = PhotoSearchSortOrder.DatePostedAsc
                Case "DatePostedDesc"
                    searchOptions.SortOrder = PhotoSearchSortOrder.DatePostedDesc
                Case "DateTakenAsc"
                    searchOptions.SortOrder = PhotoSearchSortOrder.DateTakenAsc
                Case "DateTakenDesc"
                    searchOptions.SortOrder = PhotoSearchSortOrder.DateTakenDesc
                Case "InterestingnessAsc"
                    searchOptions.SortOrder = PhotoSearchSortOrder.InterestingnessAsc
                Case "InterestingnessDesc"
                    searchOptions.SortOrder = PhotoSearchSortOrder.InterestingnessDesc
                Case "None"
                    searchOptions.SortOrder = PhotoSearchSortOrder.None
                Case "Relevance"
                    searchOptions.SortOrder = PhotoSearchSortOrder.None
            End Select

            'Dim photos As Photos
            Dim photos As Photo() = Nothing

            Select Case config.FlickrConfigurationElement.runningMode
                Case "user"
                    searchOptions.UserId = config.FlickrConfigurationElement.flickrUserId
                    photos = f.PhotosSearch(searchOptions).PhotoCollection
                Case "set"
                    'sort by interestigness
                    photos = f.PhotosetsGetPhotos(config.FlickrConfigurationElement.flickrSetId, 1, searchOptions.PerPage).PhotoCollection
                Case "tag"
                    searchOptions.Tags = config.FlickrConfigurationElement.flickrTag
                    photos = f.PhotosSearch(searchOptions).PhotoCollection
                Case "text"
                    searchOptions.Text = config.FlickrConfigurationElement.flickrSearchTerm
                    photos = f.PhotosSearch(searchOptions).PhotoCollection
                Case "group"
                    'sort by interestingness?
                    photos = f.GroupPoolGetPhotos(config.FlickrConfigurationElement.flickrGroupId, searchOptions.PerPage, 1).PhotoCollection
            End Select

            xml = "<SIMPLEVIEWER_DATA backgroundImagePath=""" & config.SimpleViewerConfigurationElement.backgroundImagePath & """ maxImageHeight=""" & config.SimpleViewerConfigurationElement.maxImageHeight & """ maxImageWidth=""" & config.SimpleViewerConfigurationElement.maxImageWidth & """ textColor=""" & config.SimpleViewerConfigurationElement.textColor & """ frameColor=""" & config.SimpleViewerConfigurationElement.frameColor & """ frameWidth=""" & config.SimpleViewerConfigurationElement.frameWidth & """ stagePadding=""" & config.SimpleViewerConfigurationElement.stagePadding & """ thumbnailColumns=""" & config.SimpleViewerConfigurationElement.thumbnailColumns & """ thumbnailRows=""" & config.SimpleViewerConfigurationElement.thumbnailRows & """ navPosition=""" & config.SimpleViewerConfigurationElement.navPosition & """ navDirection=""" & config.SimpleViewerConfigurationElement.navDirection & """ title=""" & config.SimpleViewerConfigurationElement.galleryTitle & """ imagePath=""" & imgPath & """ thumbPath=""" & thumbPath & """>"

            Dim fileLink As String

            Dim imgFile As String = "" 'for caching
            Dim thumbFile As String = "" 'for caching
            Dim imgUrl As String = "" 'for caching
            Dim thumbUrl As String = "" 'for caching
            Dim bitMap As Bitmap = Nothing
            If photos.Length > 0 Then
                For Each p As Photo In photos 'allPhotos

                    If cacheConfig.DoCreateCacheProp = False Then
                        fileLink = p.MediumUrl.Substring(p.MediumUrl.LastIndexOf("/") + 1, p.MediumUrl.Length - p.MediumUrl.LastIndexOf("/") - 1)
                    Else
                        fileLink = p.MediumUrl
                    End If


                    xml = xml & "<IMAGE>"
                    xml = xml & "<NAME>" & fileLink & "</NAME>"

                    Dim title As String = Nothing
                    Dim cartLink As String = Nothing
                    If config.SimpleViewerConfigurationElement.includeImageName = True Then
                        If config.SimpleViewerConfigurationElement.includeImageLink = True Then
                            title = "<![CDATA[<a target=""_blank""  href=""" & p.WebUrl & """>" & p.Title & "<br /><u>View Flickr Original</u></a>]]>"
                        ElseIf config.SimpleViewerConfigurationElement.includePaypalLink = "true" Then
                            cartLink = config.SimpleViewerConfigurationElement.paypalCartLink
                            cartLink &= "business=" & config.SimpleViewerConfigurationElement.paypalEmailAddress
                            cartLink &= "&amp;amount=" & config.SimpleViewerConfigurationElement.paypalPricePerItem
                            title = title & "<![CDATA[<a target=""_blank""  href=""" & cartLink & "&item_name=" & HttpUtility.HtmlEncode(p.Title) & """>" & p.Title & "<br /><u>Buy This Print</u></a>]]>"
                        Else
                            title = p.Title
                        End If

                    Else
                        title = ""
                    End If

                    title = "<CAPTION>" & title & "</CAPTION>"
                    xml = xml & title
                    xml = xml & "</IMAGE>"

                    'save image/thumb
                    If cacheConfig.DoCreateCacheProp = True Then
                        'imgFile = fileLink.Substring(fileLink.LastIndexOf("/"), fileLink.Length - fileLink.LastIndexOf("/"))
                        'med file name
                        imgFile = fileLink.Replace("/", "")  ' fileLink.Substring(p.MediumUrl.LastIndexOf("/"), p.MediumUrl.Length - p.MediumUrl.LastIndexOf("/") - 1)
                        imgUrl = p.MediumUrl
                        Select Case config.FlickrConfigurationElement.flickrImageSize
                            Case "small"
                                imgUrl = p.MediumUrl.Replace(".jpg", "_m.jpg")
                            Case "large"
                                imgUrl = p.MediumUrl.Replace(".jpg", "_b.jpg")
                        End Select
                        thumbFile = imgFile
                        thumbUrl = p.MediumUrl.Replace(".jpg", "_s.jpg")
                    End If

                    If cacheConfig.DoUseCacheProp = True Then

                        'cache images and thumb
                        If Not File.Exists(Server.MapPath(imgPath & Path.GetFileName(imgFile))) Or Not File.Exists(Server.MapPath(thumbPath & Path.GetFileName(thumbFile))) Then
                            Try
                                bitMap = bitMap.FromStream(f.DownloadPicture(imgUrl))
                                bitMap.Save(Server.MapPath(imgPath & Path.GetFileName(imgFile)), System.Drawing.Imaging.ImageFormat.Jpeg)

                                'save thumb
                                bitMap = bitMap.FromStream(f.DownloadPicture(thumbUrl))
                                bitMap.Save(Server.MapPath(thumbPath & Path.GetFileName(thumbFile)), System.Drawing.Imaging.ImageFormat.Jpeg)
                            Catch ee As Exception
                                Throw ee
                            End Try
                        End If
                    End If
                Next

                xml = xml & "</SIMPLEVIEWER_DATA>"
            End If

            Response.Clear()
            Response.ContentType = "text/xml"
            xml = "<?xml version=""1.0"" encoding=""UTF-8"" ?>" & xml

            'save xml
            If cacheConfig.DoCreateCacheProp = True Then
                '                If Not File.Exists(Server.MapPath("flickrData.xml")) Then
                File.WriteAllText(Server.MapPath("flickrData.xml"), xml)
                'End If
        End If
        Response.Write(Xml)

        End If
    End Sub
End Class